import { isExternal, toHump } from '@/utils'
import { resolve } from 'path-browserify'
import { ref } from 'vue'
import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { MenuOption, OriginRoute, SplitTab } from '../types'
import { defaultRoutes } from '@/router/routes/default-routes'

// export function loadComponents() {
//   return import.meta.glob('/src/views/**/*.vue')
// }

// export const asynComponents = loadComponents()

// export function getComponent(it: OriginRoute) {
//   return asynComponents[getFilePath(it)]
// }

export function getFilePath(it: OriginRoute) {
  if (!it.localFilePath) {
    it.localFilePath = it.menuUrl
  }
  it.localFilePath = resolve('/', it.localFilePath)
  return '/src/views' + it.localFilePath + '.vue'
}

// 过滤本地路由
export function filterRoutesFromLocalRoutes(route: OriginRoute, localRoutes: Array<RouteRecordRaw>, path = '/') {
  const filterRoute = localRoutes.find((it) => {
    return resolve(path, it.path) === route.menuUrl
  })
  if (filterRoute) {
    filterRoute.meta = {
      title: route.menuName,
      affix: !!route.affix,
      cacheable: !!route.cacheable,
      icon: route.icon,
      badge: route.badge,
      hidden: !!route.hidden,
      isRootPath: !!route.isRootPath,
      isSingle: !!route.isSingle,
      ...filterRoute.meta,
    }
    const parentPath = resolve(path, filterRoute.path)
    if (
      Array.isArray(route.children) &&
      route.children.length > 0 &&
      Array.isArray(filterRoute.children) &&
      filterRoute.children.length > 0
    ) {
      const tempChildren: RouteRecordRaw[] = []
      route.children.forEach((it: any) => {
        const childFilterRoute = filterRoutesFromLocalRoutes(it, filterRoute.children!, parentPath)
        childFilterRoute && tempChildren.push(childFilterRoute)
      })
      filterRoute.children = tempChildren
    }
  }
  return filterRoute
}

export function isMenu(it: OriginRoute) {
  return it.children && it.children.length > 0
}

export function getNameByUrl(menuUrl: string) {
  const temp = menuUrl.split('/')
  return toHump(temp[temp.length - 1])
}

// 生成路由
export function generatorRoutes(permissions: string[]) {
  // 处理首页路由
  function dealHomeRoute(homeRoute: any) {
    // 清空没有权限的router
    const permissionsChildrenRoute: any = []
    homeRoute.children.forEach((it: any) => {
      // 过滤子路由
      if (it.children) {
        it.children = it.children.filter((child: any) => {
          return child.permissions && permissions.includes(child.permissions)
        })
        if (!it.children.length) {
          return
        }
      }
      if (!it.permissions || permissions.includes(it.permissions)) {
        permissionsChildrenRoute.push(it)
      }
    })
    homeRoute.children = permissionsChildrenRoute
    // 如果没有权限，将第一个菜单（待办事项）处理为首页router
    const dashboradPermissions = 'svms:index:workplace:databoard'
    if (permissions.includes(dashboradPermissions) == false) {
      const temp = homeRoute.children.find((it: any) => it.permissions == undefined)
      temp.path = '/index/home'
      temp.meta.affix = true
    }
    return homeRoute
  }
  function filterPermissionRouters(routes: any, parent: any) {
    routes.forEach((it: any) => {
      if (it.path == '/index') {
        const homeRoute = dealHomeRoute(it)
        parent.push(homeRoute)
        return
      }
      if (it.permission) {
        if (permissions.includes(it.permission)) {
          parent.push(it)
        } else {
          return
        }
      } else {
        parent.push(it)
      }
      if (it.children && it.children.length > 0) {
        const parentRoutes = [] as Array<any>
        filterPermissionRouters(it.children, parentRoutes)
        parentRoutes && parentRoutes.length > 0 && (it.children = parentRoutes)
      }
    })
  }

  const tempRoutes = [] as Array<any>
  filterPermissionRouters(defaultRoutes, tempRoutes)
  return tempRoutes
}

// 遍历为2级路由
export function mapTwoLevelRouter(srcRoutes: Array<RouteRecordRaw>) {
  function addParentRoute(routes: any, parent: any, parentPath: string) {
    routes.forEach((it: RouteRecordRaw) => {
      if (!isExternal(it.path)) {
        it.path = resolve(parentPath, it.path)
      }
      parent.push(it)
      if (it.children && it.children.length > 0) {
        addParentRoute(it.children, parent, it.path)
      }
    })
  }
  if (srcRoutes && srcRoutes.length > 0) {
    const tempRoutes = [] as Array<any>
    srcRoutes.forEach((it) => {
      const route = { ...it }
      const parentRoutes = [] as Array<any>
      if (route.children && route.children.length > 0) {
        addParentRoute(route.children, parentRoutes, route.path)
      }
      parentRoutes && parentRoutes.length > 0 && (route.children = parentRoutes)
      tempRoutes.push(route)
    })
    return tempRoutes
  }
  return []
}

export function findAffixedRoutes(routes: Array<RouteLocationNormalized>) {
  const temp = [] as Array<RouteLocationNormalized>
  routes.forEach((it) => {
    if (it.meta && it.meta.affix) {
      if (!it.fullPath) {
        it.fullPath = it.path
      }
      temp.push(it)
    }
  })
  return temp
}

export function findCachedRoutes(routes: Array<RouteLocationNormalized>) {
  const temp = [] as Array<string>
  routes.forEach((it) => {
    if (it.name && it.meta && it.meta.cacheable) {
      temp.push(it.name as string)
    }
  })
  return temp
}

export function transfromMenu(originRoutes: Array<RouteRecordRaw>): Array<MenuOption> {
  if (!originRoutes) {
    return []
  }
  const tempMenus = [] as Array<MenuOption>
  originRoutes
    .filter((it) => (it.meta ? !it.meta.hidden : true))
    .forEach((it) => {
      const tempMenu: MenuOption = {
        key: it.path,
        label: it.meta?.title as string,
        icon: it.meta?.icon as string,
        children: null,
      }
      if (it.children) {
        if (it.meta && it.meta.isSingle && it.children.length === 1) {
          const lastItem = it.children[0] as RouteRecordRaw
          tempMenu.key = lastItem.path || tempMenu.key
          tempMenu.label = (lastItem.meta && lastItem.meta.title ? lastItem.meta?.title : tempMenu.label) as string
          tempMenu.icon = (lastItem.meta && lastItem.meta.icon ? lastItem.meta?.icon : tempMenu.icon) as string
          tempMenu.children = null
        } else {
          tempMenu.children = transfromMenu(it.children)
        }
      }
      tempMenus.push(tempMenu)
    })
  return tempMenus
}

export function transformSplitTabMenu(routes: Array<RouteRecordRaw>): Array<SplitTab> {
  const tempTabs = [] as Array<SplitTab>
  routes.forEach((it) => {
    const splitTab: SplitTab = {
      label: it.meta ? (it.meta?.title as string) : '',
      fullPath: it.path || '',
      iconPrefix: it.meta?.iconPrefix || 'icon',
      icon: it.meta ? (it.meta?.icon as any) : undefined,
      children: it.children as RouteRecordRaw[],
      checked: ref(false),
    }
    tempTabs.push(splitTab)
  })
  return tempTabs
}

export function findRouteByUrl(routes: Array<any>, path: string): RouteRecordRaw | null {
  if (!path || !routes) {
    return null
  }
  let tempRoute = null
  for (let index = 0; index < routes.length; index++) {
    const temp = routes[index]
    if (temp.path === path) {
      tempRoute = temp
      return tempRoute
    }
    if (temp.children) {
      tempRoute = findRouteByUrl(temp.children, path)
      if (tempRoute) {
        return tempRoute
      }
    }
  }
  return null
}

// 生成权限
export function generatorPermissions(res: Array<any>): string[] {
  return res.map((it) => it.permission)
}
